﻿using AutoMapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Collections.Generic;
using System.Data;
using System.Numerics;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text.RegularExpressions;
using VM.Common.DataUntil;
 
using VM.Common.Result;
using VM.Entity.EntityDto.Member;
using VM.Entity.EntityMap.Member;
using VM.Entity.EntityMap.MsgCode;
using VM.Entity.EntityMap.Token;
using VM.Entity.EntityMap.VipLevel;
using VM.IBLL.Member;
using VM.IDAL;
using static Dm.net.buffer.ByteArrayBuffer;

namespace VM.BLL.Member
{
    public class MemberBLL : BaseBLL, IMemberBLL
    {

        private readonly ISqlSuggarDAL _ISqlSuggarDAL;
        private readonly IMapper _IMapper;
        public MemberBLL(ISqlSugarClient client, ISqlSuggarDAL sqlSuggarDAL, IMapper imapper)
        {
            _ISqlSuggarDAL = sqlSuggarDAL;
            _IMapper = imapper;
        }

        /// <summary>
        /// 检查用户名、密码、公钥是否存在
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="Msg"></param>
        /// <returns></returns>


        /// <summary>
        /// 校验用户名和密码是否正确
        /// </summary>
        /// <param name="PublicKey"></param>
        /// <param name="PrivateKey"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool CheckMemberKeys(string RefreshKey, out string Msg)
        {
            int Countx = _ISqlSuggarDAL.Query<Sys_RefreshToken>(e => e.RefreshKey == RefreshKey
                                                                  && e.EndDateTimes >= DateTime.Now
                                                            ).ToList().Count();
            Msg = Countx.ToString();
            if (Countx >= 1)
            {
                return true;

            }
            else
            {
                return false;
            }


        }

        /// <summary>
        /// 添加RefreshToken值
        /// </summary>
        /// <param name="obj"></param>
        public void AddRefreshKeys(Sys_RefreshToken obj)
        {
            _ISqlSuggarDAL.InsertAsync(obj);
        }


        public sys_member MemberRegister(sys_member sys_member)
        {
            //使用注册接口
            sys_member Res = _ISqlSuggarDAL.Insert(sys_member);
            return Res;
        }




        /// <summary>
        /// 根据手机号获取当前用户信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiDataResult<sys_member> getMemberInfoByUniqStr(int typeId, string uniqStr)
        {
            if (typeId == 1)
            {
                List<sys_member> res = _ISqlSuggarDAL.Query<sys_member>(e => e.phone == uniqStr
                                                          )
                                                    .IgnoreColumns(it => new { it.pwd })
                                                    .ToList();

                if (res.Count == 1)
                {
                    return new ApiDataResult<sys_member>
                    {

                        code = 200,
                        data = res[0],
                        msg = "会员已存在"
                    };

                }
                else if (res.Count < 1)
                {

                    return new ApiDataResult<sys_member>
                    {

                        code = 403,
                        data = null,
                        msg = "会员信息不存在"
                    };
                }
                else
                {
                    return new ApiDataResult<sys_member>
                    {

                        code = 411,
                        data = null,
                        msg = "会员信息存在多条"
                    };
                }
            }
            else if (typeId == 2)
            {
                List<sys_member> res = _ISqlSuggarDAL.Query<sys_member>(e => e.wxOpenId == uniqStr
                                                          )
                                                    .IgnoreColumns(it => new { it.pwd })
                                                    .ToList();

                if (res.Count == 1)
                {
                    return new ApiDataResult<sys_member>
                    {

                        code = 200,
                        data = res[0],
                        msg = "会员已存在"
                    };

                }
                else if (res.Count < 1)
                {

                    return new ApiDataResult<sys_member>
                    {

                        code = 403,
                        data = null,
                        msg = "会员信息不存在"
                    };
                }
                else
                {
                    return new ApiDataResult<sys_member>
                    {

                        code = 411,
                        data = null,
                        msg = "会员信息存在多条"
                    };
                }
            }
            else

            {
                return new ApiDataResult<sys_member>
                {

                    code = 411,
                    data = null,
                    msg = "typeId传入错误"
                };

            }

        }

        public ApiResult CheckMemberIsExit(int checkType,string str)
        {
            if (checkType == 1)
            {
                List<sys_member> res = _ISqlSuggarDAL.Query<sys_member>(e => e.phone == str
                                                          )
                                                    .IgnoreColumns(it => new { it.pwd })
                                                    .ToList();

                if (res.Count == 1)
                {
                    return new ApiResult
                    {

                        code = 200,
                        
                        msg = "会员已存在"
                    };

                }
                else if (res.Count < 1)
                {

                    return new ApiResult
                    {

                        code = 403,
         
                        msg = "会员信息不存在"
                    };
                }
                else
                {
                    return new ApiResult
                    {

                        code = 411,
  
                        msg = "会员信息存在多条"
                    };
                }
            }
            else if (checkType == 2)
            {
                List<sys_member> res = _ISqlSuggarDAL.Query<sys_member>(e => e.wxOpenId == str
                                                          )
                                                    .IgnoreColumns(it => new { it.pwd })
                                                    .ToList();

                if (res.Count == 1)
                {
                    return new ApiResult
                    {

                        code = 200,
         
                        msg = "会员已存在"
                    };

                }
                else if (res.Count < 1)
                {

                    return new ApiResult
                    {

                        code = 403,
 
                        msg = "会员信息不存在"
                    };
                }
                else
                {
                    return new ApiResult
                    {

                        code = 411,
                 
                        msg = "会员信息存在多条"
                    };
                }
            }
            else {
                return new ApiResult
                {

                    code = 411,
           
                    msg = "传入checkType值错误"
                };

            }
        }


        public ApiDataResult<MemberInfoDto> GetMemberInfoByMemberId(int MemberId) {

            try
            {
                List<MemberInfoDto> res = _IMapper.Map<List<MemberInfoDto >>(_ISqlSuggarDAL.Query<sys_member>(e => e.id == MemberId
                                                              )
                                                        .Includes(a=>a.vipLevel)
                                                        .IgnoreColumns(it => new { it.pwd })
                                                        .ToList());
           

            
                
                if (res.Count == 1)
            {
                return new ApiDataResult<MemberInfoDto>
                {

                    code = 200,
                    data = res[0],
                    msg = "会员信息获取成功"
                };

            }
            else if (res.Count < 1)
            {

                return new ApiDataResult<MemberInfoDto>
                {

                    code = 403,
                    data = null,
                    msg = "会员信息不存在"
                };
            }
            else
            {
                return new ApiDataResult<MemberInfoDto>
                {

                    code = 411,
                    data = null,
                    msg = "会员信息存在多条"
                };
            }
            }catch (Exception e)
            {

                return new ApiDataResult<MemberInfoDto>
                {

                    code = 500,
                    data = null,
                    msg = "错误："+e.Message
                };
            }

        }


        /// <summary>
        /// 一键登录
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>

        public ApiDataResult<MemberLoginResMap> MemberSSOLogin(MemberLoginMap obj)
        {

            if (obj.loginType == 3)
            {
                //手机号一键登录


                //检验只允许含有数字和汉字和英文


                string pattern = @"^1[3-9]\d{9}$";
                bool sts = Regex.IsMatch(obj.phone, pattern);
                if (!sts)
                {
                    return new ApiDataResult<MemberLoginResMap>
                    {
                        code = 401,
                        msg = "手机号格式不正确",
                        data = null

                    };


                }
                try
                {
                    List<sys_member> resultList = _ISqlSuggarDAL.Query<sys_member>(e => e.phone == obj.phone
                                                          ).ToList();
                    if (resultList.Count == 1)
                    {
                        MemberLoginResMap member = new MemberLoginResMap();
                        member.id = resultList[0].id.ToString();
                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 200,
                            msg = "登录成功",
                            data = member

                        };
                    }
                    else if (resultList.Count < 1)
                    {

                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 401,
                            msg = "当前用户不存在",
                            data = null

                        };

                    }
                    else
                    {

                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 401,
                            msg = "当前用户存在多条，不允许登录",
                            data = null

                        };
                    }
                }
                catch (Exception e)
                {
                    return new ApiDataResult<MemberLoginResMap>
                    {
                        code = 401,
                        msg = "登录出错：" + e.Message,
                        data = null

                    };

                }
            }
            else if (obj.loginType == 4)
            {
                //微信公众号openid一键登录
                //检验只允许含有数字和汉字和英文

                try
                {
                    List<sys_member> resultList = _ISqlSuggarDAL.Query<sys_member>(e => e.wxOpenId == obj.wxOpenId
                                                          ).ToList();
                    if (resultList.Count == 1)
                    {
                        MemberLoginResMap member = new MemberLoginResMap();
                        member.id = resultList[0].id.ToString();
                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 200,
                            msg = "登录成功",
                            data = member

                        };
                    }
                    else if (resultList.Count < 1)
                    {

                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 401,
                            msg = "当前用户不存在",
                            data = null

                        };

                    }
                    else
                    {

                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 401,
                            msg = "当前用户存在多条，不允许登录",
                            data = null

                        };
                    }
                }
                catch (Exception e)
                {
                    return new ApiDataResult<MemberLoginResMap>
                    {
                        code = 401,
                        msg = "登录出错：" + e.Message,
                        data = null

                    };

                }





            }
            else

            {

                return new ApiDataResult<MemberLoginResMap>
                {
                    code = 411,
                    msg = "登录类型值传入错误",
                    data = null

                };

            }





        }

        /// <summary>
        /// 验证码登录
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public ApiDataResult<MemberLoginResMap> MemberMsgLogin(MemberLoginMap obj)
        {


            //检验只允许含有数字和汉字和英文
            string pattern = @"^1[3-9]\d{9}$";
            bool sts = Regex.IsMatch(obj.phone, pattern);
            if (!sts)
            {
                return new ApiDataResult<MemberLoginResMap>
                {
                    code = 401,
                    msg = "手机号格式不正确",
                    data = null
                };
            }
            try
            {
                //获取当前时间的时间戳
                long currentDate = Timestamp.getNowTimeStamp();
                List<sys_message> resultList = _ISqlSuggarDAL.Query<sys_message>(e => e.phone == obj.phone
                                                                            && (long)e.endDate >= currentDate
                                                                            && e.code.ToString() == obj.code.ToString()
                                                      ).ToList();
                if (resultList.Count == 1)
                {
                    //根据手机号获取当前用户信息
                    List<sys_member> userResultList = _ISqlSuggarDAL.Query<sys_member>(e => e.phone == obj.phone
                                                     ).ToList();
                    MemberLoginResMap member = new MemberLoginResMap();
                    member.id = resultList[0].id.ToString();
                    return new ApiDataResult<MemberLoginResMap>
                    {
                        code = 200,
                        msg = "登录成功",
                        data = member

                    };
                }

                else
                {

                    return new ApiDataResult<MemberLoginResMap>
                    {
                        code = 401,
                        msg = "验证码已过期",
                        data = null

                    };
                }
            }
            catch (Exception e)
            {
                return new ApiDataResult<MemberLoginResMap>
                {
                    code = 401,
                    msg = "登录出错：" + e.Message,
                    data = null

                };

            }
        }


        /// <summary>
        /// 账号密码登录
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public ApiDataResult<sys_member> MemberPwdLogin(MemberLoginMap obj)
        {


            //检验只允许含有数字和汉字和英文
            string pattern = @"^1[3-9]\d{9}$";
            bool sts = Regex.IsMatch(obj.phone, pattern);
            if (!sts)
            {
                return new ApiDataResult<sys_member>
                {
                    code = 401,
                    msg = "手机号格式不正确",
                    data = null
                };
            }
            try
            {
                //判断当前账号是否存在
                List<sys_member> checkIsExit = _ISqlSuggarDAL.Query<sys_member>(e => e.phone == obj.phone
                                                                                ).ToList();
                if (checkIsExit.Count == 1)
                {

                    //获取当前时间的时间戳
                    BigInteger currentDate = Timestamp.getNowTimeStamp();
                    List<sys_member> resultList = _ISqlSuggarDAL.Query<sys_member>(e => e.phone == obj.phone
                                                                                     && e.pwd == obj.passWord  ).ToList();
                    if (resultList.Count == 1)
                    {

                        MemberLoginResMap member = new MemberLoginResMap();
                        member.id = resultList[0].id.ToString();
                        return new ApiDataResult<sys_member>
                        {
                            code = 200,
                            msg = "登录成功",
                            data = resultList[0]

                        };
                    }

                    else
                    {

                        return new ApiDataResult<sys_member>
                        {
                            code = 401,
                            msg = "账号或密码错误",
                            data = null

                        };
                    }
                }
                else if (checkIsExit.Count < 1)
                {

                    return new ApiDataResult<sys_member>
                    {
                        code = 410,
                        msg = "账号不存在",
                        data = null

                    };
                }
                else
                {

                    return new ApiDataResult<sys_member>
                    {
                        code = 411,
                        msg = "账号不存在",
                        data = null

                    };

                }



            }
            catch (Exception e)
            {
                return new ApiDataResult<sys_member>
                {
                    code = 401,
                    msg = "登录出错：" + e.Message,
                    data = null

                };

            }
        }




        /// <summary>
        /// 
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public Task<bool> updateMemberNameById(int MemberId, sys_member obj){

            Task<bool> b  = _ISqlSuggarDAL.UpdateAsync<sys_member>(obj);
            return b;


}


    }



}
